///import core
///commands 远程图片抓取
///commandsName  catchRemoteImage,catchremoteimageenable
///commandsTitle  远程图片抓取
/**
 * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
 */
UE.plugins[ "catchremoteimage" ] = function() {
    var me = this,vm = {},
        ajax = UE.ajax,
        total_image = 0,
        catched = 0,
        catch_failed = 0;
    
    /* 设置默认值 */
    if ( me.options.catchRemoteImageEnable === false ) return;
    me.setOpt( {
        catchRemoteImageEnable: false,
    } );
    me.isCatchingRemoteImage = false;

    me.addListener( "afterpaste", function() {
        setTimeout(function() {
        	me.fireEvent( "catchRemoteImage" );
        }, 800);
    } );

    me.addListener( "clearDoc", function() {
        if ( me.isCatchingRemoteImage ) {
            me.isCatchingRemoteImage = false;
            me.fireEvent( "afterCatchRemoteImage" );
        }
    } );

    me.addListener( "catchRemoteImage", function() {
        var catcherLocalDomain = me.getOpt( "catcherLocalDomain" ),
            catcherActionUrl = me.getActionUrl( "catchimage" ), 
            catcherUrlPrefix = me.getOpt( "catcherUrlPrefix" ),
            catcherFieldName = me.getOpt( "catcherFieldName" ),
            uploadFormData = me.getOpt( "uploadFormData" );

        uploadFormData[ "appkey" ] = me.getOpt( "appkey" );

        var allUrls = [];
        var this_time_image = 0;
        var test = function( src, urls ) {
            if (
                src.indexOf( location.host ) != -1 ||
                /(^\.)|(^\/)/.test( src )
            ) {
                return true;
            }
            if ( urls ) {
                for ( var j = 0, url;
                    ( url = urls[ j++ ] ); ) {
                    if ( src.indexOf( url ) !== -1 ) {
                        return true;
                    }
                }
            }
            return false;
        };
        
        var sections = UE.dom.domUtils.getElementsByTagName( me.document, "section" );
        var catchBgImageFromSection = function(){
        	for (var i = 0, ci; (ci = sections[i++]);) {
    			var bgurl = "";
    			var style = ci.getAttribute("style");
    			if (style) {
    				style = style.replace("&amp;", "&");
    				var reg = new RegExp("['|\"]\\s*(http[s]?://[^;\\)]+?)['|\"]","i");
    				var match = style.match(reg);
    				if (match && match[0]) {
    					bgurl = match[1];
    				} else {
    					var reg = new RegExp("\\(\\s*(http[s]?://[^;\\)\\s]+?)\\)", "i");
    					var match = style.match(reg);
    					if (match && match[0]) {
    						bgurl = match[1];
    					}
    				}

    				if (bgurl != "" && /^(https?|ftp):/i.test(bgurl) && !test(bgurl, catcherLocalDomain) ) {
    					this_time_image++;
    					catchBgImage(bgurl, ci);
    				}
    			}
    		}
        }
        catchBgImageFromSection();
        
		var svgs = UE.dom.domUtils.getElementsByTagName( me.document, "svg" );
		var catchBgImageFromTagSvg = function(){
			for (var i = 0, ci; (ci = svgs[i++]);) {
				var bgurl = "";
				var style = ci.getAttribute("style");
				if (style) {
					style = style.replace("&amp;", "&");
					var reg = new RegExp("['|\"]\\s*(http[s]?://[^;\\)]+?)['|\"]","i");
					var match = style.match(reg);
					if (match && match[0]) {
						bgurl = match[1];
					} else {
						var reg = new RegExp("\\(\\s*(http[s]?://[^;\\)\\s]+?)\\)","i");
						var match = style.match(reg);
						if (match && match[0]) {
							bgurl = match[1];
						}
					}

					if (bgurl != "" && /^(https?|ftp):/i.test(bgurl) && !test(bgurl, catcherLocalDomain) ) {
						this_time_image++;
						catchBgImage(bgurl, ci);
					}
				}
			}
		}
		catchBgImageFromTagSvg();
		
		var remoteImages = [];
        var imgs = UE.dom.domUtils.getElementsByTagName( me.document, "img" );
        var catchImageFromTagImg = function(){
        	for (var i = 0, ci; (ci = imgs[i++]);) {
    			if (ci.getAttribute("word_img")) {
    				continue;
    			}
    			ci.removeAttribute("data-src");
    			var src = ci.getAttribute("_src") || ci.src || "";
    			if ( src != "" && /^(https?|ftp):/i.test(src) && !test(src, catcherLocalDomain) ) {
    				remoteImages.push(src);
    			}
    		}

            if ( remoteImages.length ) {
                var opt = {
                    //成功抓取
                    success: function( r ) {
                        try {
                            var info =
                                r.state !== undefined ?
                                r :
                                eval( "(" + r.responseText + ")" );
                        } catch ( e ) {
                            return;
                        }

                        /* 获取源路径和新路径 */
                        var i,
                            j,
                            ci,
                            cj,
                            oldSrc,
                            newSrc,
                            list = info.list;

                        if ( list && list.length > 0 ) {
                            for ( i = 0; i < imgs.length; i++ ) {
                            	ci = imgs[ i ];
                                oldSrc = ci.getAttribute( "_src" ) || ci.src || "";

                                for ( j = 0; j < list.length; j++ ) {
                                    cj = list[ j ];
                                    if ( ( oldSrc == cj.source || oldSrc.replace( "&amp;", "&" ) == cj.source.replace( "&amp;", "&" ) ) && cj.state == "SUCCESS" ) {
                                        //抓取失败时不做替换处理
                                        newSrc = catcherUrlPrefix + cj.url;
                                        ci = $(me.document).find('img[src=\"' + cj.source + '\"]');
                                        ci.attr("src", newSrc);
                                        ci.attr("_src", newSrc);
                                        break;
                                    }
                                }
                            }
                            catched++;
                            me.fireEvent( "showmessage", {
                                id: "catchimage-msg",
                                content: "第" +
                                    catched +
                                    "张远程图片成功保存，共" +
                                    total_image +
                                    "张",
                                type: "success",
                                timeout: 3000,
                            } );
                        }

                        checkCatchFinishState();
                    },
                    //回调失败，本次请求超时
                    error: function() {
                        me.fireEvent( "catchremoteerror" );
                        catch_failed++;
                        checkCatchFinishState();
                    },
                };

                for ( var i = 0; i < remoteImages.length; i++ ) {
                    var oimgs = [];
                    oimgs.push( remoteImages[ i ] );
                    catchremoteimage(oimgs, opt); // 单个图片处理，防止多了超时
                }
            }
        }
        catchImageFromTagImg();
        
        this_time_image += remoteImages.length;
        if ( this_time_image > 0 ) {
            total_image += this_time_image;
            if ( !me.isCatchingRemoteImage ) { 
            	me.fireEvent( "beforeCatchRemoteImage" );
                me.isCatchingRemoteImage = true;
            }
        }
        if ( this_time_image > 0 ) {
            me.fireEvent( "showmessage", {
                id: "catchimage-msg",
                content: "有" + this_time_image + "张远程图片需要保存",
                type: "success",
                timeout: 3000,
            } );
        }

        me.addListener("catchremoteerror", function () {
            catch_failed ++;
            me.fireEvent('showmessage', {
                'id': 'catchimage-msg',
                'content': '有'+catch_failed+'张远程图片保存失败，共'+total_image+'张',
                'type': 'error',
                'timeout': 3000
            });
        });

        function catchBgImage( bgurl, ci ) {
            var params = UE.utils.serializeParam( me.queryCommandValue( "serverparam" ) ) || "";
			params = 'access_token=' + JSON.parse(window.sessionStorage.getItem("token")) + (params ? '&' + params : '');
            var url = UE.utils.formatUrl(catcherActionUrl + (params ? (( catcherActionUrl.indexOf( "?" ) == -1 ? "?" : "&" ) + params) : "") );
            var isJsonp = UE.utils.isCrossDomainUrl( url );
            var imgs = [];
            imgs.push( bgurl );
            var opt = {
                method: "POST",
                dataType: isJsonp ? "jsonp" : "",
                timeout: 60000, //单位：毫秒，回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
                onsuccess: function( r ) {
                    try {
                        var info = r.state !== undefined ? r : eval( "(" + r.responseText + ")" );
                    } catch ( e ) {
                        return;
                    }
                    /* 获取源路径和新路径 */
                    var j, cj, newSrc, list = info.list;
                    if ( list && list.length > 0 ) {
                        for ( j = 0; j < list.length; j++ ) {
                            cj = list[ j ];
                            var nodeName = ci.nodeName;
                            var style = ci.getAttribute( "style" );
                            var spell = style.replace(/\"/g,'\\"').replace(/\'/g,"\\'");
                            ci = $(me.document).find(nodeName + '[style=\"' + spell + '\"]');
                            if ( ( bgurl == cj.source || bgurl == cj.source.replace( "&amp;", "&" ) ) &&  cj.state == "SUCCESS" ) {
                                //抓取失败时不做替换处理
                                newSrc = catcherUrlPrefix + cj.url;
                                ci.attr("style", style.replace( bgurl, newSrc ));
                                //ci.setAttribute( "style", style.replace( bgurl, newSrc ) );
                                break;
                            }
                        }
                        catched++;
                        me.fireEvent( "showmessage", {
                            id: "catchimage-msg",
                            content: "第" +
                                catched +
                                "张远程图片成功保存，共" +
                                total_image +
                                "张",
                            type: "success",
                            timeout: 3000,
                        } );
                    }
                    checkCatchFinishState();
                },
                onerror: function() {
                    me.fireEvent( "catchremoteerror" );
                    catch_failed++;
                    checkCatchFinishState();
                }
            };
            
        	if ( me.getOpt( 'catcherUploadMode' ) === 'single' ) {
                for ( var i = 0; i < imgs.length; i++ ) {
                    opt[ catcherFieldName ] = imgs[ i ];
                    opt[ "data" ] = uploadFormData;
                    ajax.request( url, opt );
                }
            } else {
                opt[ catcherFieldName ] = imgs;
                opt[ "data" ] = uploadFormData;
                ajax.request( url, opt );
            }            	
        }

        function catchremoteimage( imgs, callbacks ) {
            var params = UE.utils.serializeParam( me.queryCommandValue( "serverparam" ) ) || "";
			params = 'access_token=' + JSON.parse(window.sessionStorage.getItem("token")) + (params ? '&' + params : '');
			var url = UE.utils.formatUrl(catcherActionUrl + (params ? (( catcherActionUrl.indexOf( "?" ) == -1 ? "?" : "&" ) + params) : "") );
            var isJsonp = UE.utils.isCrossDomainUrl( url );
            var opt = {
                    method: "POST",
                    dataType: isJsonp ? "jsonp" : "",
                    timeout: 60000, //单位：毫秒，回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
                    onsuccess: callbacks[ "success" ],
                    onerror: callbacks[ "error" ]
                };
            if ( me.getOpt( 'catcherUploadMode' ) === 'single' ) {
                for ( var i = 0; i < imgs.length; i++ ) {
                    opt[ catcherFieldName ] = imgs[ i ];
                    opt[ "data" ] = uploadFormData;
                    ajax.request( url, opt );
                }
            } else {
                opt[ catcherFieldName ] = imgs;
                opt[ "data" ] = uploadFormData;
                ajax.request( url, opt );
            }
        }

        function checkCatchFinishState() {
            if ( parseInt(total_image) == (parseInt(catched) + parseInt(catch_failed)) && me.isCatchingRemoteImage ) {
                me.isCatchingRemoteImage = false;
                total_image = catched = catch_failed = 0;
                me.fireEvent( "afterCatchRemoteImage" );
            }
        }
    } );
};